package com.cwz.springboot.crawlerfirst.crawler.get;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpGetTest {

    public static void main(String[] args) {

        // 1. 打开浏览器，创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 2. 输入网址，发起get请求并创建HttpGet对象
        HttpGet httpGet = new HttpGet("http://106.15.37.148/testdisplay/a.html");

        // 配置请求信息
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(1000) // 创建连接的最长时间，单位是毫秒
                .setConnectionRequestTimeout(500) // 设置请求(获取连接)的最长时间，单位是毫秒
                .setSocketTimeout(10*1000) // 设置数据传输的最长时间，单位是毫秒
                .build();
        //给请求设置请求信息
        httpGet.setConfig(config);

        CloseableHttpResponse response = null;

        try {
            // 3. 按回车，发起请求，返回响应，使用HttpClient对象发起请求
            response = httpClient.execute(httpGet);

            // 4. 解析响应，获取数据
            // 判断状态码是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = response.getEntity();
                String content = EntityUtils.toString(httpEntity, "utf8");
                System.out.println("响应报文的长度：" + content.length());
                System.out.println(content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 5. 关闭httpClient
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}
